import React, { useEffect, useState } from 'react';
import { Form, Input, Button, DatePicker, Table, message, Modal, InputNumber } from 'antd';
import moment from 'moment';
import Search from 'antd/es/input/Search';
import { getBooksByPage, searchBookByName } from '../../api/book';

const { Item } = Form;

const Fraction = () => {
    const [form] = Form.useForm();
    const [books, setBooks] = useState<any[]>([]);
    const [isModalVisible, setIsModalVisible] = useState(false);
    const [currentPage, setCurrentPage] = useState(1); // 添加
    const [pageContent, setPageContent] = useState<any>({});
    const [editingBook, setEditingBook] = useState<any>(null);

    const columns = [
        { title: '书名', dataIndex: 'name', key: 'name' },
        { title: '作者', dataIndex: 'author', key: 'author' },
        { title: 'ISBN', dataIndex: 'isbn', key: 'isbn' },
        { title: '评分', dataIndex: 'rating', key: 'rating',render: (text: number, record: any) => (
            <a onClick={() => {setEditingBook(record)
                form.setFieldsValue({  // 修改为 setFieldsValue
                    rating: record.rating,
                    name: record.name,
                    author: record.author,
                    isbn: record.isbn,
                });
            }}>
                {text || '点击评分'}
            </a>
        ) },
    ];

    const onFinish = (values: any) => {
        const newBook = {
            ...values,
            publishDate: values.publishDate.format('YYYY-MM-DD'),
            key: books.length,
        };
        setBooks([...books, newBook]);
        form.resetFields();
        setIsModalVisible(false);
        message.success('图书信息已录入');
    };

    const handleSearch = async (e: any) => {
        const res: any = await searchBookByName({
          name: e,
          page: 0,
          size: 10,
        });
    
        setBooks(res?.data?.content);
        setPageContent({...pageContent,totalElements: res?.data?.content?.length})
      };

    const showModal = () => {
        setIsModalVisible(true);
    };

    const handleCancel = () => {
        setIsModalVisible(false);
    };

    const getData = async (page = 0) => {
        const res: any = await getBooksByPage({ page: page, size: 10 });
        const resultList = res?.data?.content ?? [];
       
        setBooks(resultList);
        setPageContent(res.data)
      };

      const handleTableChange = (pagination: any) => {
        setCurrentPage(pagination.current);
        getData(Number(pagination?.current) - 1); // 后端页码从0开始，前端从1开始
      };

    useEffect(() => {
        getData();
    }, []);

    const handleRatingSubmit = async (values: any) => {
        try {
            // 这里调用API更新评分
            // await updateBookRating({ bookId: editingBook.key, rating: values.rating });
            setBooks(books.map(book => 
                book.name === editingBook.name ? {...book, rating: values.rating} : book
            ));
            setEditingBook(null);
            form.resetFields();
            message.success('评分更新成功');
        } catch (error) {
            message.error('评分更新失败');
        }
    };

    return (
        <div style={{ padding: '20px' }}>
            {/* <Button type="primary" onClick={showModal} style={{ marginBottom: '20px' }}>
        添加图书
      </Button> */}
            <Search
                placeholder="搜索书名"
                onSearch={handleSearch}
                style={{ marginBottom: 16, width: 300, marginRight: 16 }}
            />
             { !!editingBook && <Modal
                title="添加图书"
                open={!!editingBook}
                footer={null}
                onOk={() => form.submit()}
                onCancel={() => setEditingBook(null)}
            >
                <Form form={form}  onFinish={handleRatingSubmit}
                initialValues={{ ...editingBook }} layout="vertical">
                    <Item name="name" label="书名" rules={[{ required: true, message: '请输入书名' }]}>
                        <Input />
                    </Item>
                    <Item name="author" label="作者" rules={[{ required: true, message: '请输入作者' }]}>
                        <Input />
                    </Item>
                    <Item name="isbn" label="ISBN" rules={[{ required: true, message: '请输入ISBN' }]}>
                        <Input />
                    </Item>
                    <Item name="rating" label="评分" rules={[{ required: true, message: '请输入评分' }]}>
                        <InputNumber min={0} max={100} />
                    </Item>
                    <Item>
                        <Button type="primary" htmlType="submit">
                            提交
                        </Button>
                    </Item>
                </Form>
            </Modal>
            }
            <Table columns={columns} dataSource={books} style={{ marginTop: '20px' }} 
               onChange={handleTableChange}
               pagination={{ pageSize: 10, total: pageContent?.totalElements ?? 0, showSizeChanger: false, current: currentPage }}
            />
        </div>
    );
};

export default Fraction;